package com.hadoop.project.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

import static com.hadoop.project.entity.constant.QQConstant.QQ_EMAIL_PASSWORD;
import static com.hadoop.project.entity.constant.QQConstant.QQ_EMAIL_USERNAME;


public class QQEmailUtil {

    /**
     * 发送邮件使用方法<br>
     * String recipientEmail = "3791792845@qq.com";<br>
     * String verificationCode = "2234";<br>
     * qqEmailutil.sendEmail(recipientEmail,verificationCode);<br>
     * 发送完毕<br>
     * <br>
     *
     * @author 智哥
     * @param toEmail 收件人邮箱地址
     * @param code 验证码
     * @throws Exception 邮件发送失败
     * @return void 没有返回值
     */
    public static void sendEmail(String toEmail, String code,String htmlContent) throws Exception {
        // 配置邮件服务器属性
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.qq.com");
        properties.put("mail.smtp.port", "587");

        // 创建会话对象
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(QQ_EMAIL_USERNAME, QQ_EMAIL_PASSWORD);
            }// 创建邮件消息对象
        });

        try {
            // 创建邮件消息对象
            Message message = new MimeMessage(session);
            // 设置发件人
            message.setFrom(new InternetAddress(QQ_EMAIL_USERNAME));
            // 设置收件人
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
            // 设置邮件主题
            message.setSubject("验证码");
            // 设置邮件内容
            String htmlContent1=htmlContent + code + "</strong>。</p>" +
                    "<p>有效期为 5 分钟，请尽快完成验证。</p>" +
                    "<a href='https://baidu.com'>立即前往</a>" +
                    "<p>如果这不是您本人的操作，请忽略此邮件。</p>" +
                    "</body></html>";
            message.setContent(htmlContent1, "text/html; charset=utf-8");

            // 发送邮件
            Transport.send(message);

            System.out.println("邮件发送成功");
        } catch (MessagingException e) {
            String exceptionMessage = e.getMessage();
            // 判断是否是因为接收方邮箱不存在导致的错误
            if (exceptionMessage != null && (exceptionMessage.contains("550") || exceptionMessage.contains("recipient"))) {
                System.out.println("接收方邮箱不存在，请检查邮箱地址。");
            } else {
                System.out.println("邮件发送失败，原因：" + exceptionMessage);
                e.printStackTrace();
            }
        }
    }
}

